package com.google.appengine.a4ieve.filters;

import com.google.appengine.a4ieve.Const;
import com.google.appengine.a4ieve.Helper;
import com.google.appengine.a4ieve.entities.CuratorWrapper;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.UserServiceFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

public class StudentGroupFilter implements Filter{

    private static final Logger LOG = Logger.getLogger(StudentGroupFilter.class.getName());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //nothing here
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //here we have to query the database and get the group name
        String email = UserServiceFactory.getUserService().getCurrentUser().getEmail();
        LOG.severe("Entered email: " + email);
        String key = Helper.cropEmailId(email);
        Query curatorQuery = new Query(CuratorWrapper.KIND_KEY).addProjection(CuratorWrapper.GROUP_KEY_PROJECTION).
                addFilter(
                        CuratorWrapper.USER_ID_PROPERTY,
                        Query.FilterOperator.EQUAL,
                        key
                );
        DatastoreService service = DatastoreServiceFactory.getDatastoreService();
        Entity storedEntity = service.prepare(curatorQuery).asSingleEntity();
        if (storedEntity == null) {
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not associated with any group. Go away, " +
                    UserServiceFactory.getUserService().getCurrentUser().getEmail());
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            String groupId = (String)storedEntity.getProperty(CuratorWrapper.GROUP_KEY_PROPERTY);
            LOG.severe("Setting group id to " + groupId);
            request.getSession().setAttribute(Const.GROUP, groupId);
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        //nothing here
    }
}
